package com.cssy.xxkj.attach.dao.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.springframework.web.multipart.MultipartFile;

import com.byd.acegiext.domain.User;
import com.cssy.xxkj.attach.dao.AttachFileUploadDAO;
import com.cssy.xxkj.attach.entity.AttachFileUploadBaseDirDO;
import com.cssy.xxkj.attach.entity.AttachFileUploadDO;
import com.cssy.xxkj.attach.util.ArrayUtils;
import com.cssy.xxkj.attach.util.CommConstants;
import com.cssy.xxkj.attach.util.CommUtils;
import com.plat.util.IDCodeTypeUtil;
import com.plat.util.SessionUtil;

public class AttachFileUploadDAOImpl extends SqlMapClientDaoSupport implements AttachFileUploadDAO{

	@Resource(name = "attachFileUploadBaseDirDAO")
	AttachFileUploadBaseDirDAOImpl  attachFileUploadBaseDirDAO;
	
	@Override
	public void save(HttpServletRequest request,MultipartFile file, String projectId, String projectType,
			String fileCategory) {
		
		String saveType = CommConstants.SAVE_TYPE_DISK;
		AttachFileUploadBaseDirDO attachFileUploadBaseDir = null;
		if("0".equals(saveType)){
			attachFileUploadBaseDir  = attachFileUploadBaseDirDAO.createAttachBaseDir(request);
		}
		
		User user = SessionUtil.getUser(request);
		AttachFileUploadDO attachFileUpload = this.saveFileBySaveType(saveType, attachFileUploadBaseDir, file, fileCategory,CommConstants.FILE_RELATED_YES, user);
		
		if(StringUtils.isNotBlank(projectType)){
			attachFileUpload.setProjectId(projectId);
			attachFileUpload.setProjectType(projectType);
		}
		
		getSqlMapClientTemplate().insert("AttachFileUpload.insert", attachFileUpload);
	}
	
	@Override
	public Map saveTemp(HttpServletRequest request,MultipartFile file, String projectId, String projectType,
			String fileCategory) {
		
		String saveType = CommConstants.SAVE_TYPE_DISK;
		AttachFileUploadBaseDirDO attachFileUploadBaseDir = null;
		if("0".equals(saveType)){
			attachFileUploadBaseDir  = attachFileUploadBaseDirDAO.createAttachBaseDir(request);
		}
		
		User user = SessionUtil.getUser(request);
		AttachFileUploadDO attachFileUpload = this.saveFileBySaveType(saveType, attachFileUploadBaseDir, file, fileCategory,CommConstants.FILE_RELATED_SAVE,user);
		
		if(StringUtils.isNotBlank(projectType)){
			attachFileUpload.setProjectId(projectId);
			attachFileUpload.setProjectType(projectType);
		}
		
		getSqlMapClientTemplate().insert("AttachFileUpload.insert", attachFileUpload);
		Map map = new HashMap();
		map.put("id", attachFileUpload.getId()+"");
		map.put("fileName", attachFileUpload.getFileName());
		map.put("fileContentType", attachFileUpload.getFileContentType());
		map.put("fileSize", attachFileUpload.getFileSize());
		
		return map;
	}
	
	private AttachFileUploadDO saveFileBySaveType(String saveType,AttachFileUploadBaseDirDO attachFileUploadBaseDir,MultipartFile file,String fileCategory,String fileRelated,User user){
		
		AttachFileUploadDO attachFileUpload = new AttachFileUploadDO();
		// 基本信息
		attachFileUpload.setId(IDCodeTypeUtil.getId());
		attachFileUpload.setFileName(file.getOriginalFilename());
		attachFileUpload.setFileContentType(file.getContentType());
		attachFileUpload.setFileCategory(fileCategory);
		attachFileUpload.setFileRelated(fileRelated);
		attachFileUpload.setUploadUser(user.getId()+"");
		attachFileUpload.setUploadUserName(user.getName());
		attachFileUpload.setUploadDate(new Date());
		// 存入磁盘
		if("0".equals(saveType)) {
			//先监测一下目录是否已经成功mount，注意：不要自动创建目录
			//一个 NFS 目录可能会挂在挂载失败，自动创建目录的话，会导致覆盖原来nfs目录
			String detectMountDir = CommConstants.UPLOAD_BASE_DIR;
			File detectMountDirFile = new File(detectMountDir);
			if(detectMountDirFile==null || !detectMountDirFile.exists()){
				throw new RuntimeException("文件存放目录不存在，请创建文件目录："+detectMountDir);
				
			}
			attachFileUpload.setSaveType(CommConstants.SAVE_TYPE_DISK);
			attachFileUpload.setBaseDirId(attachFileUploadBaseDir==null?null:attachFileUploadBaseDir.getId());
			attachFileUpload.setFileSize(file.getSize());
			attachFileUpload.setDiskPath(CommUtils.saveUploadFile(attachFileUploadBaseDir.getDirPath(),file));
			
		} else {
			//存入数据库,暂时不支持
		}
		
		return attachFileUpload;
	}
	
	@Override
	public AttachFileUploadDO findByPrimaryKey(String id){
		
		 AttachFileUploadDO fileUploadDO = (AttachFileUploadDO) getSqlMapClientTemplate().queryForObject("AttachFileUpload.findByPrimaryKey", id);
		
		return fileUploadDO;
	}

	@Override
	public List<AttachFileUploadDO> findFileUploadByIds(List<String> attachIds){
		List<AttachFileUploadDO> fileUploads = new ArrayList<AttachFileUploadDO>();
		List<List<String>> attachIdList = ArrayUtils.splitToFixedList(attachIds, 100);
		for(List<String> _attachIdList : attachIdList){
			for(String attachId : _attachIdList){
				if(StringUtils.isBlank(attachId)){
					continue;
				}
				AttachFileUploadDO attachFileUploadDO = this.findByPrimaryKey(attachId);
				if(!fileUploads.contains(attachFileUploadDO)){
					fileUploads.add(attachFileUploadDO);
				}
			}
		}
		return fileUploads;
	}
	
	@Override
	public List<AttachFileUploadDO> findFileUpDOsByProjectId(String projectId){
		return getSqlMapClientTemplate().queryForList("AttachFileUpload.findByProjectId", projectId);
	}
	
	@Override
	public List<AttachFileUploadDO> findAttachFileUploadDOs(Map<String,String> paramsMap){
		return getSqlMapClientTemplate().queryForList("AttachFileUpload.findFileUpladsByMap", paramsMap);
	}
	
	@Override
	public int deleteFileUpload(String id){
		//逻辑删除,不物理删除
		Map<String,String> map = new HashMap<String,String>();
		map.put("id", id);
		map.put("fileRelated", CommConstants.FILE_RELATED_NO);
		return getSqlMapClientTemplate().delete("AttachFileUpload.updateRelatedByMap", map);
		
	}
	
	@Override
	public void update(AttachFileUploadDO attachFileUploadDO){
		getSqlMapClientTemplate().update("AttachFileUpload.update", attachFileUploadDO);
	}
	
	/**
	 * 更改附件的有效性，及与业务对象的关联关系
	 */
	@Override
	public void updateFileRelated(String idStr,String projectId,String projectType,String fileCategory){
		if(StringUtils.isNotBlank(idStr)){
			Map<String,String> paramMap = new HashMap<String,String>();
			paramMap.put("projectId", projectId);
			paramMap.put("projectType", projectType);
			paramMap.put("fileCategory", fileCategory);
			paramMap.put("fileRelated", CommConstants.FILE_RELATED_YES);
			List<String> attachIds = CommUtils.splitIds(idStr);
			for(String attachId : attachIds){
				if(StringUtils.isBlank(attachId)){
					continue;
				}
				paramMap.put("id", attachId);
				getSqlMapClientTemplate().update("AttachFileUpload.updateRelatedByMap", paramMap);
			}
		}
	}
}
